<template>
  <div>
    <el-card>
      <el-row>角色管理</el-row> <el-divider></el-divider>
      <el-row>
        <el-col :span="12">
          <el-input
            style="width: 240px; margin: 10px"
            v-model="serachModel.roleName"
            placeholder="角色名称"
          ></el-input>
          <el-button type="primary" @click="getAllRoles">查询</el-button>
        </el-col>
        <el-col :span="12" align="right"
          ><el-button
            type="primary"
            icon="el-icon-plus"
            circle
            @click="OpenEditUi(null)"
          ></el-button
        ></el-col>
      </el-row>
      <el-divider></el-divider>

      <el-row>
        <el-table :data="roles" v-loading="loading">
          <el-table-column label="#" width="140">
            <template slot-scope="scope">
              {{
                (serachModel.pageNo - 1) * serachModel.pageSize +
                scope.$index +
                1
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleDesc"
            width="140"
          ></el-table-column>
          <el-table-column label="管理路由">
            <template slot-scope="scope">
              <el-button size="mini" @click="openMenuUi(scope.row)"
                >设置路由</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click="OpenEditUi(scope.row.roleId)"
                >编辑</el-button
              >
              <br />
              <el-button
                type="text"
                style="color: red"
                @click="deleteRoleById(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="serachModel.pageNo"
        :page-sizes="[10, 20, 40, 60]"
        :page-size="serachModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 角色信息编辑对话框 -->
    <el-dialog
      @close="cleaForm"
      :title="title"
      :visible.sync="dialogFormVisible"
      width="24%"
    >
      <el-form :model="roleForm" :rules="rules" ref="roleFormRef">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input
            v-model="roleForm.roleName"
            autocomplete="off"
            placeholder="角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色中文名称"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input
            v-model="roleForm.roleDesc"
            autocomplete="off"
            placeholder="角色中文名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设置用户路由 -->
    <el-dialog title="路由设置" :visible.sync="dialogVisibleMenu" width="30%">
      <el-tree
        :data="menus"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleMenu = false">取 消</el-button>
        <el-button type="primary" @click="saveMenu">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/userManage";
import menuApi from "@/api/menu";
import roleMenuApi from "@/api/roleMenu";
import rolusApi from "@/api/roles";
export default {
  data() {
    return {
      roles: [],
      serachModel: {
        pageNo: 1,
        pageSize: 10,
      },

      dialogVisibleMenu: false,
      roleId: "",

      menus: [],
      total: 0,
      title: "",

      dialogFormVisible: false,

      roleForm: {},

      formLabelWidth: "180px",

      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 4,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],

        roleDesc: [
          { required: true, message: "请输入角色中文名称", trigger: "blur" },
          {
            min: 2,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
        ],
      },

      loading: false,
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.serachModel.pageSize = pageSize;
      this.getAllRoles();
    },
    handleCurrentChange(pageNo) {
      this.serachModel.pageNo = pageNo;
      this.getAllRoles();
    },

    cleaForm() {
      this.roleForm = {};
      if (
        this.$refs.roleFormRef != null ||
        this.$refs.roleFormRef != undefined
      ) {
        this.$refs.roleFormRef.clearValidate();
      }
    },

    // 查询所有角色名称
    getAllRoles() {
      this.loading = true;
      rolusApi.getRoles(this.serachModel).then((response) => {
        this.roles = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 打开对话框UI
    OpenEditUi(id) {
      if (id == null) {
        this.title = "新增角色";
      } else {
        this.title = "修改角色";
        // 更具Id查询用户
        rolusApi.getRoleById(id).then((response) => {
          this.roleForm = response.data;
        });
      }
      this.dialogFormVisible = true;
    },

    // 保存用户信息
    saveRole() {
      // 触发表达验证
      this.$refs.roleFormRef.validate((valid) => {
        if (valid) {
          // 提交数据给后台
          rolusApi.saveRole(this.roleForm).then((response) => {
            // 成功提示
            this.$message({
              showClose: true,
              message: "操作成功",
              type: "success",
            });
            // 关闭对话框
            this.dialogFormVisible = false;
            // 刷新表单
            this.getAllRoles();
          });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.loading = false;
          return false;
        }
      });
    },

    // 删除角色
    deleteRoleById(row) {
      this.$confirm(
        `此操作将永久删除该角色${row.roleDesc}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        rolusApi.deleteRoleyId(row.roleId).then((response) => {
          this.$message({
            type: "success",
            message: response.message,
          });
          // 刷新
          this.getAllRoles();
        });
      });
    },

    getAllMenus() {
      // 获取菜单路由
      menuApi.getMenus().then((response) => {
        this.menus = response.data;

        // 设置显示的菜单信息
        var selectMenuList = [];
        this.menus.forEach((item) => {
          var menu = {
            id: item.id,
            label: item.nameZh,
            children: [],
          };
          if (
            item.children != null &&
            item.children != null &&
            item.children.length > 0
          ) {
            item.children.forEach((children) => {
              var children = {
                id: children.id,
                label: children.nameZh,
              };
              menu.children.push(children);
            });
          }
          selectMenuList.push(menu);
        });

        this.menus = selectMenuList;
      });
    },

    // 打开设置路由菜单
    openMenuUi(row) {
      this.roleId = row.roleId;

      // 回显数据

      roleMenuApi.getRoleMenu(this.roleId).then((response) => {
        var keys = [];
        response.data.forEach((item) => {
          keys.push(item.menuId);
        });

        this.$refs.tree.setCheckedKeys(keys);
      });

      this.dialogVisibleMenu = true;
    },

    // 保存选择的Menu
    saveMenu() {
      // this.$refs.tree.setCheckedKeys([3]);
      var sendData = {
        id: this.roleId,
        menuIds: this.$refs.tree.getCheckedKeys(),
      };
      roleMenuApi.saveRoleMenu(sendData).then((response) => {
        this.$message.success(response.message);
        // 关闭对话框
        this.dialogVisibleMenu = false;
      });
    },
  },

  created() {
    this.getAllRoles();

    this.getAllMenus();
  },
};
</script>

<style scoped></style>
